import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';

///特殊作业-自定义气体选择样式控件
///[title] 标题
///[gasList] 已有的数据列表
///[onCallBack] 选择回调
///[isEnabled] 是否可编辑
///[isShowGasName] 是否显示气体名称(代表性气体)
///[isShowDivider] 是否显示分割线
///[isShowTitle] 是否显示气体标题
class CustomSelectGasPage extends StatefulWidget {
  const CustomSelectGasPage({
    required this.title,
    required this.gasList,
    required this.onCallBack,
    super.key,
    this.isEnabled = true,
    this.isShowGasName = true,
    this.isShowDivider = true,
    this.isShowTitle = true,
  });

  final String title;
  final List<ExecuteTicketGasListWorkGasJsonDTOList> gasList;
  final Function(List<ExecuteTicketGasListWorkGasJsonDTOList>) onCallBack;
  final bool isEnabled;
  final bool isShowGasName;
  final bool isShowDivider;
  final bool isShowTitle;

  @override
  State<CustomSelectGasPage> createState() => _CustomSelectGasPageState();
}

class _CustomSelectGasPageState extends State<CustomSelectGasPage> {
  // List<ExecuteTicketGasListWorkGasJsonDTOList> dateList = [];

  @override
  initState() {
    super.initState();
    _initDate();
  }

  /// 初始化数据
  void _initDate() {
    //添加数据
    if (widget.gasList.isEmpty || !widget.gasList.any((obj) => obj.gasTypeName == widget.title)) {
      _addList();
    }
  }

  ///添加检测数据
  void _addList() {
    final ExecuteTicketGasListWorkGasJsonDTOList gasBean = ExecuteTicketGasListWorkGasJsonDTOList();
    gasBean.gasTypeName = widget.title;
    switch (widget.title) {
      case '有毒有害气体':
        gasBean.gasQualified = '≤GBZ2.1等相关标准';
        gasBean.gasName = '相关气体';
        break;
      case '可燃气体':
        gasBean.gasQualified = '≤爆炸下限大于等于4%，其浓度不大于0.5%（体积分数）；下限小于4%，其浓度不大于0.2%等相关标准';
        gasBean.gasName = '相关气体';
        break;
      case '氧气含量':
        gasBean.gasQualified = '19.5~21%(体积分数)';
        break;
      default:
        break;
    }
    widget.gasList.add(gasBean);
    // if (widget.title != '氧气含量') {
    //   widget.gasList.add(ExecuteTicketGasListWorkGasJsonDTOList()..gasTypeName = widget.title);
    // } else {
    //   widget.gasList.add(ExecuteTicketGasListWorkGasJsonDTOList()
    //     ..gasTypeName = widget.title
    //     ..gasQualified = '19.5~21%(体积分数)');
    // }
  }

  // ///回调给外部
  // void _callBack() {
  //   widget.onCallBack(dateList);
  // }

  ///获取输入框显示
  Widget _getInputView({
    required int type,
    required String value,
    required ExecuteTicketGasListWorkGasJsonDTOList workGas,
    String? hintText,
  }) {
    final TextEditingController controller = TextEditingController(text: value);
    controller.selection = TextSelection.fromPosition(TextPosition(offset: controller.text.length));
    String title = '';
    switch (type) {
      case 0:
        title = '代表性气体';
        break;
      case 1:
        title = '合格标准';
        break;
      case 2:
        title = '分析结果';
        break;
    }
    return Row(
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.1,
            color: AppColors.font_color_black,
          ),
        ),
        AppGaps.hGap20,
        Expanded(
            child: TextField(
          enabled: widget.isEnabled,
          controller: controller,
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF262F38),
            fontWeight: FontWeight.w400,
          ),
          textAlign: TextAlign.right,
          textDirection: TextDirection.rtl,
          decoration: InputDecoration(
            hintText: hintText ?? (widget.isEnabled ? '请输入' : '暂无'),
            isCollapsed: true,
            border: const OutlineInputBorder(borderSide: BorderSide.none),
            hintStyle: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
              color: AppColors.text_grey,
            ),
          ),
          onChanged: (value) {
            switch (type) {
              case 0:
                workGas.gasName = value.toString();
                break;
              case 1:
                workGas.gasQualified = value.toString();
                break;
              case 2:
                workGas.gasResult = value.toString();
                break;
            }
          },
        )),
      ],
    );
  }

  ///获取分割线
  Widget _getDivider() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.w),
      child: Divider(
        height: 1.w,
        color: const Color(0xFFE6E7EB),
      ),
    );
  }

  ///获取气体分析
  Widget _getGasView(ExecuteTicketGasListWorkGasJsonDTOList dateList, int index) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.symmetric(vertical: 10.w),
      padding: EdgeInsets.symmetric(horizontal: 18.w, vertical: 14.w),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F7F7),
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        children: [
          //代表性气体
          Visibility(
            visible: widget.isShowGasName,
            child: //代表性气体
                Column(
              children: [
                _getInputView(
                  type: 0,
                  value: dateList.gasName ?? '',
                  workGas: dateList,
                ),
                _getDivider(),
              ],
            ),
          ),
          //分析结果
          _getInputView(
            type: 2,
            value: dateList.gasResult ?? '',
            workGas: dateList,
          ),
        ],
      ),
    );
  }

  /// 获取合格标准提示显示
  Widget _getQualifiedDisplayPrompt() {
    // 从字典中查找id相同的作业对象
    final gasBean = widget.gasList.firstWhere((other) => other.gasTypeName == widget.title,
        orElse: ExecuteTicketGasListWorkGasJsonDTOList.new);
    if(gasBean.gasQualified!.isEmpty){
      return Container();
    }
    return Container(
      margin: EdgeInsets.only(top: 10.w,left: 10.w,right: 10.w),
      child: Text(
        gasBean.gasQualified!,
        style: TextStyle(
          color: const Color(0xff262F38).withOpacity(0.6),
          height: 1.2,
          fontWeight: FontWeight.w400,
          fontSize: 11.sp,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // AppGaps.vGap16,
            // Row(
            // children: [
            // Text(
            //   widget.title,
            //   style: TextStyle(
            //       color: const Color(0xff262F38),
            //       height: 1.2,
            //       fontWeight: FontWeight.w400,
            //       fontSize: 14.sp),
            // ),
            // const Spacer(),
            // Visibility(
            //     visible: widget.isEnabled,
            //     child: Text(
            //       '添加检测',
            //       style: TextStyle(
            //           color: const Color(0xff5C6DFF),
            //           height: 1.2,
            //           fontWeight: FontWeight.w400,
            //           fontSize: 12.sp),
            //     ).clickOnce(() {
            //       _addList();
            //       setState(() {});
            //     })),
            // ],
            // ),
            AppGaps.vGap10,

            Visibility(
              visible: widget.isShowTitle,
              child: Text(
                widget.title,
                style: TextStyle(
                    color: const Color(0xff262F38),
                    height: 1.2,
                    fontWeight: FontWeight.w400,
                    fontSize: 14.sp),
              ),
            ),
            // 获取合格标准提示显示
            _getQualifiedDisplayPrompt(),
            // Visibility(
            //   visible: widget.gasList.isNotEmpty,
            //   child: AppGaps.vGap16,
            // ),
            ListView.separated(
              itemCount: widget.gasList.length,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                final ExecuteTicketGasListWorkGasJsonDTOList workGas = widget.gasList[index];
                if (widget.title != widget.gasList[index].gasTypeName) {
                  return Container();
                }
                return Container(
                  alignment: Alignment.center,
                  child: _getGasView(workGas, index),

                  /// 注释的地方为气体分析数据可以多选,业务需求改为单选
                  // Stack(
                  //   alignment: Alignment.topRight,
                  //   children: [
                  //     //获取气体分析
                  //     _getGasView(workGas, index),
                  //     //删除按钮
                  //     Visibility(
                  //         visible: widget.isEnabled,
                  //         child: const Icon(
                  //           Icons.highlight_remove,
                  //           color: Color(0xFFFD6B6B),
                  //         ).clickOnce(() {
                  //           widget.gasList.remove(workGas);
                  //           // _callBack();
                  //           setState(() {});
                  //         }))
                  //   ],
                  // ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Container();
              },
            ),
            AppGaps.vGap12,
            Visibility(
                visible: widget.isShowDivider,
                child: Divider(
                  height: 1.w,
                  color: AppColors.bg_color_grey,
                )),
          ],
        ));
  }
}
